package cn.vivi.oss.service.impl;

import cn.vivi.oss.service.OssService;
import cn.vivi.oss.util.ConfigObj;
import cn.vivi.oss.util.StringUtils;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {

    @Autowired
    private ConfigObj configObj;

    @Override
    public String uploadFile(MultipartFile file) {
        OSS ossClient = new OSSClientBuilder().build(configObj.getEndpoint(), //
                configObj.getAccessKeyId(), //
                configObj.getAccessKeySecret());
        try {
            InputStream  inputStream = file.getInputStream();
            String fileName = UUID.randomUUID().toString().replace("-", "") + "@" + file.getOriginalFilename();
            ossClient.putObject(configObj.getBucket(), configObj.getFilePath() + fileName, inputStream);
            return configObj.getBaseUrl() + fileName;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            ossClient.shutdown();
        }
    }

    @Override
    public boolean deleteFile(String filePath) {
        String endpoint = configObj.getEndpoint();
        String accessKeyId = configObj.getAccessKeyId();
        String accessKeySecret = configObj.getAccessKeySecret();
        String bucketName = configObj.getBucket();
        // 填写文件完整路径。文件完整路径中不能包含Bucket名称。
        String objectName = StringUtils.splitFilePath(filePath);
        OSS ossClient = null;
        try {
            ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            ossClient.deleteObject(bucketName, objectName);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return  false;
        } finally {
            ossClient.shutdown();
        }
    }

}
